﻿(function ($, undefined) {
    
    var localizedText = {
        emptyText: '<i>Click \'Edit\' button on the top - right to edit this text...</i>',
        editQuestion: 'Edit Question',
        addQuestion: '"Add New Question',
        moveUp: 'Move Up',
        moveDown: 'Move Down',
        'delete': 'Delete',
        deleteConfirm: 'Are you sure you want to delete?',
        errQuestionText: 'The question No [0] is left blank.',
        errNotEnoughOption: 'The question No [0] has too few options. A question must have at least 2 options.',
        errOptionBlank: 'The question No [0] has an option that is left blank.',
        errEditBlank: 'The text area is blank. Are you sure you want to continue?',
        errNoQuestion: 'There is no question to save...',
        errNoCorrectOption: 'The question No [0] has no correct option.'
    };

    var editorOptions = {
        toolbar :
        [
        ['Source'],
        ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
        ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
        ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
        ['Link','Unlink','Anchor'],
        ['Image','Table','HorizontalRule','PageBreak','Iframe'],
        ['Maximize', 'ShowBlocks','-','About'],
        ],
        skin: "v2"
    };
    
    var questionTemplate = {
        text: '',
        reason: '',
        options: []
    };

    var optionTemplate = {
        text: '',
        isCorrect: false
    };

    var resetQuestionIndex = function () {
        var index = 1;
        $(".question-items").find(".question-item")
            .not("#question-item-template")
            .each(function () {
                $(this).find(".number-area").html("" + index);
                index++;
            });
    };

    var questionContainer = $(".question-items");

    var createQuestion = function (question) {
        var mQuestion = $.extend({}, questionTemplate);
        mQuestion = question ? $.extend(mQuestion, question) : mQuestion;

        var item = $("#question-item-template").clone()
                .appendTo(questionContainer)
                .removeAttr("id");

        item.find(".row-template").remove();

        if (mQuestion.id && mQuestion.id > 0) {
            item.find(".question-id").val("" + mQuestion.id);
        }

        if (mQuestion.text == '') {
            item.find(".text-question").html(localizedText.emptyText);
        } else {
            item.find(".text-question").html(mQuestion.text)
                .removeClass("empty");
        }


        if (mQuestion.reason == '') {
            item.find(".question-reason").html(localizedText.emptyText);
        } else {
            item.find(".question-reason").html(mQuestion.reason)
                .removeClass("empty");
        }

        var createOption = function (option) {
            var mOption = $.extend({}, optionTemplate);
            mOption = option ? $.extend(mOption, option) : mOption;

            var optionRow = $(".row-template")
                            .clone()
                            .appendTo(item.find(".options-table tbody"))
                            .removeClass("row-template");

            if (mOption.id && mOption.id > 0) {
                optionRow.find(".option-id").val("" + mOption.id);
            }

            optionRow.find("input.text").val(mOption.text);

            if (mOption.isCorrect) {
                optionRow.find(".check-is-correct").prop("checked", "checked");
            }

            var table = optionRow.parents(".options-table");
            var resetIndex = function () {
                var optionIndex = 1;
                table.find(".option-row")
                    .each(function () {
                        $(this).find(".option-index").html("" + optionIndex);
                        optionIndex++;
                    });
            };

            optionRow.find(".option-up").click(function () {
                var prev = optionRow.prev();

                if (prev.length > 0 && prev.hasClass("option-row")) {
                    optionRow.insertBefore(prev);
                }

                resetIndex();
            });

            optionRow.find(".option-down").click(function () {
                var next = optionRow.next();

                if (next.length > 0 && next.hasClass("option-row")) {
                    optionRow.insertAfter(next);
                }

                resetIndex();
            });

            optionRow.find(".option-delete").click(function () {
                if (confirm(localizedText.deleteConfirm)) {
                    optionRow.remove();
                    resetIndex();
                }
            });

            resetIndex();
        };

        if (mQuestion.options && mQuestion.options.length > 0) {
            $.each(mQuestion.options, function () {
                createOption(this);
            });
        }

        item.find(".create-option-button").click(createOption);

        item.find(".question-down").click(function () {
            var next = item.next();

            if (next.length > 0 && next.hasClass("question-item") && !next.is("#question-item-template")) {
                next.slideUp(function () {
                    $(this).insertBefore(item).slideDown(function () {
                        resetQuestionIndex();
                    });
                });
            }
        });

        item.find(".question-up").click(function () {
            var prev = item.prev();

            if (prev.length > 0 && prev.hasClass("question-item") && !prev.is("#question-item-template")) {

                prev.slideUp(function () {
                    $(this).insertAfter(item).slideDown(function () {
                        resetQuestionIndex();
                    });
                });
            }
        });

        item.find(".question-delete").click(function () {
            if (confirm(localizedText.deleteConfirm)) {
                item.remove();
                resetQuestionIndex();
            }
        });

        item.find(".button-edit").click(function () {
            var $this = $(this);
            var target = $this.next();
            var editor = null;
            $("#textEdit").val(target.html());
            $.fancybox({
                href: '#edit-form',
                modal: false,
                width: '600px',
                height: '680px',
                openEffect: 'none',
                closeEffect: 'none',
                beforeClose: function () {
                    if (editor) {
                        editor.destroy(); CKEDITOR.remove(editor);
                    }                    
                }

            });

            editor = CKEDITOR.replace("textEdit", editorOptions);

            $(".editform-done-button").unbind("click")
                .bind("click", function () {
                    var text = editor.getData();

                    if ($.trim(text).length > 0 || confirm(localizedText.errEditBlank)) {

                        target.html(text);

                        if (target.hasClass("empty")) {
                            target.removeClass("empty");
                        }
                        $.fancybox.close();
                    }
                });
        });

        resetQuestionIndex();

        item.show();

        return item;
    };

    var initialized = false;

    var context = {
        token: '',
        action: ''
    };
        
    $.adminQuestions = function () {
        if (initialized) return;
        else initialized = true;
                
        if (arguments.length > 0) {
            context = $.extend(context, arguments[0]);
        }

        if (arguments.length > 1) {
            $(arguments[1]).click(function () {
                var item = createQuestion();
                if (item) {
                    $('body').animate({
                        scrollTop: item.offset().top
                    }, 500);
                }
            });
        }

        if (arguments.length > 2) {
            localizedText = $.extend(localizedText, arguments[2]);
        }

        if (arguments.length > 3) {
            if ($.isArray(arguments[3]) && arguments[3].length > 0) {
                $.each(arguments[3], function () {
                    createQuestion(this);
                });
            } else {
                createQuestion(arguments[3]);
            }
        } else {
            createQuestion();
        }
    };

    var focusElement = function (element) {
        $('body').animate({
            scrollTop: $(element).offset().top
        }, 500);
    };

    var validateQuestion = function (element) {
        var el = $(element);
        var index = el.find(".number-area").html();
        var result = true;

        var questionElement = el.find(".text-question");

        if (questionElement.hasClass("empty") || $.trim(questionElement.html()).length == 0) {
            focusElement(el);
            alert(localizedText.errQuestionText.replace(/\[0\]/g, index));
            return false;
        }

        var options = el.find(".option-row");

        if (options.length <= 1) {
            focusElement(el);
            alert(localizedText.errNotEnoughOption.replace(/\[0\]/g, index));
            return false;
        }

        var hasCheckedOption = false;
        $.each(options, function () {
            var $this = $(this);

            if ($this.find("input.check-is-correct").is(":checked")) {
                hasCheckedOption = true;
            }

            if ($.trim($this.find("input.text").val()) == '') {
                result = false;

                focusElement(el);
                alert(localizedText.errOptionBlank.replace(/\[0\]/g, index));
                return false; // break
            }
        });

        if (!hasCheckedOption) {
            alert(localizedText.errNoCorrectOption.replace(/\[0\]/g, index));
            return false; // break
        }

        return result;
    };

    var validateForm = function () {

        var questions = $(".question-item")
            .not("#question-item-template");

        if (questions.length == 0) {
            alert(localizedText.errNoQuestion);
            return false;
        } else {
            var result = true;
            questions.each(function () {
                if (!validateQuestion(this)) {
                    result = false;
                    return false; // break
                }
            });
            return result;
        }
    };

    var saveForm = function () {
        var data = [];
        var displayIndex = 0;
        $(".question-item")
            .not("#question-item-template")
            .each(function () {
                var $this = $(this);

                var reasonElement = $this.find(".question-reason");
                var item = {
                    id: $this.find(".question-id").val(),
                    text: $this.find(".text-question").html(),
                    displayIndex: displayIndex,
                    reason: reasonElement.hasClass("empty") ? '' : reasonElement.html(),
                    options: []
                };

                var optionDisplayIndex = 0;
                $this.find(".option-row").each(function () {
                    var row = $(this);
                    item.options.push({
                        id: row.find(".option-id").val(),
                        text: row.find("input.text").val(),
                        displayIndex: optionDisplayIndex,
                        isCorrect: row.find("input.check-is-correct").is(":checked")
                    });

                    optionDisplayIndex++;
                });

                data.push(item);

                displayIndex++;
            });

        // post the form
        var form = $("<form method='POST'>")
            .appendTo("body");

        var tokenElement = $("<input type='hidden'/>")
            .appendTo(form)
            .attr('name', '__RequestVerificationToken')
            .val(context.token);

        var dataElement = $("<input type='hidden'/>")
            .appendTo(form)
            .attr('name', 'data')
            .val(JSON.stringify(data));
        
        form.submit();
    };

    $(document).ready(function () {        
        editorOptions.enterMode = CKEDITOR.ENTER_BR;
        $(".editform-cancel-button").click(function () {
            $.fancybox.close();
        });

        $("#save-button").click(function () {
            if (!validateForm()) {
                return;
            } else {
                saveForm();
            }
        });
    });
})(jQuery);